from sqlalchemy import select
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import Mapped, relationship
from .base import Base, str_150, str_50
from app.models import session_factory


class Student(Base):
    __tablename__ = 'students'

    first_name: Mapped[str_50]
    last_name: Mapped[str_50]
    phone: Mapped[str_50]
    email: Mapped[str_150]
    average_score: Mapped[int | None]
    scholarship: Mapped[bool | None]

    @classmethod
    def get_student_by_scholarship(cls):
        # получить список студентов, которые имеют стипендию
        with (session_factory() as session):
            students = session.execute(select(Student)
                                       .filter(Student.scholarship == True)
                                       ).unique().all()
            students_list = []
            for student in students:
                students_list.append(student[0].to_json())
            return students_list

    @classmethod
    def get_students_by_high_average_score(cls, input_score):
        # получить список студентов, у которых средний балл выше, чем тот балл,
        # который будет передан входным параметром в функцию
        with session_factory() as session:
            students = session.query(Student).filter(Student.average_score > input_score).all()
            students_list = []
            for student in students:
                students_list.append(student.to_json())
            return students_list

    def __repr__(self):
        return self.first_name + " " + self.last_name

    def __getitem__(self, item):
        return getattr(self, item)

    def to_json(self):
        return {c.name: f'{getattr(self, c.name)}' for c in self.__table__.columns}

    student_receiving_books = relationship(
        "ReceivingBook",
        back_populates="student_with_book",
        cascade="all, delete-orphan",
        lazy="joined"
    )

    receive = association_proxy("student_receiving_books", "book")
